package com.ruoyi.yl.process.impl;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.api.util.HttpUtils;
import com.ruoyi.yl.domain.Users;
import com.ruoyi.common.domain.body.WeChatLoginBody;
import com.ruoyi.yl.process.WeChatLoginProcess;
import com.ruoyi.yl.service.IUsersService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


@Service
public class WeChatLoginProcessImpl implements WeChatLoginProcess {


    @Resource
    private TokenService tokenService;


    @Resource
    private IUsersService userService;

    @Resource
    private IUsersService usersService;


    @Override
    public WxSessionResult login(WeChatLoginBody body) {
        //1.使用code去微信换取openId 和 wxSessionKey
        WxSessionResult wxSessionResult = getSessionKeyAndOpenId(body.getCode());

        String openId = wxSessionResult.openId();
        String sessionKey = wxSessionResult.wxSessionKey();

        if (openId == null || sessionKey == null) {
            return null;
        }


        //判断当前openId 有查询 返回 没有创建

        Users users = usersService.selectByOpenId(openId);
        if (ObjectUtils.isEmpty(users)) {
            //初始化新用户
            users = usersService.initUser(Users.builder()
                    .nickname("微信注册用户")
                    .openid(openId)
                    .points(0)
                    .creditScore(100)
                    .status(1)
                    .build());
        }

        //更新用户最后登录时间 数据库
        recordLoginInfo(users.getId());
        //创建token 并且缓存登录信息redis 提供给jwt过验证
        Map<String, Object> token = tokenService.createWxToken(LoginUser.builder()
                .users(users.getWxUser())
                .build());
        return new WxSessionResult(openId, sessionKey, (String) token.get("access_token"));
    }


    @Override
    public void updateUserInfo(String nickName, String phoneNumber, String avatarUrl) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Users users = userService.selectByOpenId(loginUser.getUsers().getOpenid());
            users.setNickname(nickName);
            users.setPhone(phoneNumber);
            users.setAvatarUrl(avatarUrl);

            //更新数据库
            userService.updateById(users);

            //更新缓存
            loginUser.setUsers(users.getWxUser());

            //更新redis
            tokenService.refreshToken(loginUser);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private WxSessionResult getSessionKeyAndOpenId(String code) {
        String appid = "wxb1bfa2961b2c6328";
        String secret = "f8d5e50857523f0d97e187d29dae3410";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        // 发送请求
        String response = HttpUtils.sendGet(url);
        JSONObject json = JSONObject.parseObject(response);
        String openid = json.getString("openid");
        String sessionKey = json.getString("session_key");
        return new WxSessionResult(openid, sessionKey, null);
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {

        usersService.updateLoginTime(userId);

    }



}
